import smtplib
import os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email import encoders
import datetime
import time

projectPath = os.getcwd()

t = time.strftime("%Y%m%d", time.localtime())

# dir =  projectPath+'/report'

dir =  projectPath+'/compress_report'

# 获取当前当前目录下的文件列表
def file_name(dir):
    print(dir)
    fileList = ''
    for root, dirs, files in os.walk(dir):
        fileList = files

    return fileList

# 筛选需要发送的文件
def filter_file():
    # 存储需要发送的文件列表
    sendList = []
    d = datetime.datetime.now().strftime('%Y%m%d')
    fileList = file_name(dir)
    print('fileList',fileList)
    for i in range(len(fileList)):
        if d in fileList[i]:
            sendList.append(fileList[i])
    # print(sendList)
    return sendList

# 判断是否生成当天的报告
def judge_file():
    # gen_bool = False
    send_list = filter_file()
    lenth =  len(send_list)
    if lenth == 0:
         return False
    else:
         return  True




def sendEmail():
    d = datetime.datetime.now().strftime('%Y-%m-%d')
    user = 'zhaoyueling@huayun.com'
    pwd = '9ZYLZXM@tf'

    #
    # to = ['zhaoyueling@huayun.com','lizhouchen@huayun.com','shenyuefang@huayun.com']
    to = ['zhaoyueling@huayun.com']

    string = '详情见附件！！'
    msg = MIMEMultipart()
    msg['Subject'] = d + '用例执行报告'

    content1 = MIMEText(string, 'plain', 'utf-8')
    msg.attach(content1)

    attfiles =  filter_file()

    # 添加附件
    for i in range(len(attfiles)):
        attfile = dir+'\\'+attfiles[i]
        print(attfile)
        basename = os.path.basename(attfile)
        fp = open(attfile, 'rb')
        att = MIMEText(fp.read(), 'base64', 'utf-8')
        att["Content-Type"] = 'application/octet-stream'
        att.add_header('Content-Disposition', 'attachment', filename=('gbk', '', basename))
        encoders.encode_base64(att)
        msg.attach(att)

    # -----------------------------------------------------------se
    try:
        s = smtplib.SMTP('smtp.huayun.com')
        s.login(user, pwd)
        s.sendmail(user, to, msg.as_string())
        print('发送成功')
        s.close()
    except smtplib.SMTPException as e:
        print(e)

def send():
    # filter_file()
    bool = judge_file()

    if bool == True:
        sendEmail()
    else:
        print('no report')

if __name__ == "__main__":

    send()
